package com.ccx.library.module.login.service;

import cn.hutool.core.lang.func.VoidFunc0;
import cn.hutool.cron.task.Task;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ccx.library.exception.FreezeException;
import com.ccx.library.exception.LoginException;
import com.ccx.library.module.user.entity.User;
import com.ccx.library.module.user.service.UserService;
import com.ccx.library.response.R;
import com.ccx.library.util.JwtProvide;
import com.ccx.library.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class LoginService {
    @Autowired
    private UserService userService;
    public Object Login(User user) throws LoginException, FreezeException {
        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        queryWrapper.eq("password",Md5Util.Encryption(user.getPassword()));
        return isFlag(user,queryWrapper);
    }
    public Map isFlag(User user,QueryWrapper queryWrapper) throws LoginException, FreezeException {
        User query = userService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(query)){
            throw new LoginException();
        }
        if (!Md5Util.encode(user.getPassword(),query.getPassword())) {
            throw new LoginException();
        }
        if (query.getStatus().equals(1)){
            throw new FreezeException();
        }
        /**
         * 生成token
         */
        Map<String,Object> map=new HashMap<>();
        map.put("username",query.getUsername());
        map.put("userId",query.getUserId());
        map.put("status",query.getStatus());
        Map token = JwtProvide.getToken(map);
        long startTime = System.currentTimeMillis();
        saveToken(token);
        long endTime = System.currentTimeMillis();
        System.out.println("redis保存程序运行时间：" + (endTime - startTime) + "ms");
        return token;
    }

    /**
     * 登录凭证存入redis
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${token.expire}")
    private Long time;
    @Async
    public void saveToken(Map token){
        String key = (String) token.get("key");
        redisTemplate.opsForValue().set(key,token.get("token"),time, TimeUnit.MINUTES);
    }
}
